package com.magic233.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.magic233.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: AdminInterceptor
 * Description:
 * date: 2021/5/30 14:34
 * author: zouyuan
 */
public class ManagerInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入部门负责人拦截器");
        String token = request.getParameter("token");
        System.out.println(token);
        if (token == null) {
            System.out.println("未登录");
            response.sendRedirect(request.getContextPath() + "/user/noLogin");
            return false;
        } else {
            Users user = (Users) redisTemplate.opsForValue().get(token);
            if (user == null) {
                System.out.println("未登录");
                response.sendRedirect(request.getContextPath() + "/user/noLogin");
                return false;
            } else {
                System.out.println(user.getUsername() + " " + user.getPhone() + " " + "已登录");
                //刷新过期时间
                redisTemplate.expire(token, 30, TimeUnit.MINUTES);
                for (String role :
                        user.getRole()) {
                    System.out.println(role);
                    if ("manager".equals(role)) {
                        request.setAttribute("user", user);
                        return true;
                    }
                }
                System.out.println("权限不足");
                response.sendRedirect(request.getContextPath() + "/user/noPermissions");
                return false;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
